<template>
  <el-dialog v-model="visible" :title="title" width="720" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="120" size="default"
        label-position="top">
        <div class="title">基础信息</div>

        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item label="仓库名称" prop="warehouse_name">
              <el-input v-model="form.warehouse_name" placeholder="请输入" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="仓库编码" prop="warehouse_code">
              <div class="flex">
                <el-input style="width: 200px;" class="w-full" v-model="form.warehouse_code" placeholder="请输入"
                  :disabled="handleType == 'view'"></el-input>
                <el-switch class="ml-2" v-model="form.status" inline-prompt active-text="启用" inactive-text="禁用"
                  :active-value='1' :inactive-value='0' :disabled="handleType == 'view'" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="仓库属性" prop="wms_attribute">
              <el-select class="w-full" v-model="form.wms_attribute" placeholder="请选择" :disabled="handleType != 'add'">
                <el-option v-for="item in props.options['base.warehouse']?.[0].wmsAttributeType" :key="item.value"
                  :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="所属平台">
              <el-select class="w-full" v-model="form.wms_platform" placeholder="请选择" :disabled="handleType != 'add'"
                @change="changePlatform">
                <el-option v-for="item in props.options['base.warehouse']?.[0].wmsPlatformType" :key="item.value"
                  :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="店铺">
              <el-select class="w-full" v-model="form.shop_id" placeholder="请选择" :disabled="handleType != 'add'">
                <el-option v-for="item in shopOptions" :key="item.shop_id" :label="item.shop_name" :value="item.shop_id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="所属国家" prop="country">
              <SelectCountry class="w-full" v-model="form.country" placeholder="请选择" :disabled="handleType == 'view'">
              </SelectCountry>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="省份">
              <el-input v-model="form.province" placeholder="请输入联系人" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="城市">
              <el-input v-model="form.city" placeholder="请输入联系人" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详细地址">
          <el-input v-model="form.address" placeholder="请输入详细地址" :disabled="handleType == 'view'"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="联系人">
              <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="联系方式">
              <el-input v-model="form.phone" placeholder="请输入" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="邮政编号">
              <el-input v-model="form.zip_code" placeholder="请输入邮政编号" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="邮箱">
              <el-input v-model="form.email" placeholder="请输入邮箱" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">第三方API管理</div>
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Token" :required="form.api_active_status == 1">
              <el-input v-model="form.api_token" placeholder="请输入Token" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="App Key" :required="form.api_active_status == 1">
              <el-input v-model="form.api_app_key" placeholder="请输入App Key" :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="API地址" :required="form.api_active_status == 1">
              <div class="flex">
                <el-input style="width: 200px;" v-model="form.api_url" placeholder="请输入API地址"
                  :disabled="handleType == 'view'"></el-input>
                <el-switch class="ml-2" v-model="form.api_active_status" inline-prompt active-text="启用" inactive-text="禁用"
                  :active-value='1' :inactive-value='0' :disabled="handleType == 'view'" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="库容" prop="volume">
              <el-input v-model="form.volume" placeholder="请输入库容" :disabled="handleType == 'view'">
                <template #append>m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="一品多位">
              <el-select class="w-full" v-model="form.sku_more_location_status" placeholder="请选择"
                :disabled="handleType == 'view'">
                <el-option v-for="item in props.options['base.warehouse']?.[0].skuMoreLocationStatus" :key="item.value"
                  :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品最大货位数" :prop="form.sku_more_location_status == 1 ? 'max_location_num' : ''">
              <el-input v-model="form.max_location_num" placeholder="请输入产品最大货位数"
                :disabled="handleType == 'view'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <template #footer>
      <template v-if="handleType == 'view'">
        <div class="flex justify-center py-2">
          <el-button type="" @click="close">关 闭</el-button>
        </div>
      </template>
      <div class="flex justify-center py-2" v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getWarehouseDetail, savaWarehouse, updateWarehouse } from '../api/index'
import { queryCountry, getShopList } from '@/api/public'
import { reactive, ref, toRefs, computed, inject } from 'vue'
import { ElMessage } from 'element-plus'
import SelectCountry from '@/components/SelectCountry'

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])
const props = defineProps({
  options: {
    type: Object,
    default: {}
  }
})

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    warehouse_name: [{
      required: true, message: '请输入仓库名称', trigger: 'blur'
    }],
    warehouse_code: [{
      required: true, message: '请输入仓库编码', trigger: 'blur'
    }],
    wms_attribute: [{
      required: true, message: '请输入仓库属性', trigger: 'blur'
    }],
    country: [{
      required: true, message: '请选择所属国家', trigger: 'change'
    }],
    volume: [{
      required: true, message: '请输入库容', trigger: 'blur'
    }],
    max_location_num: [{
      required: true, message: '请输入最大货位数', trigger: 'blur'
    }],
  },
  shopOptions: []
})
const { form, title, handleType, rules, shopOptions } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    sku_more_location_status: 0,
    status: 1
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getWarehouseDetail({
      id
    })
    form.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const changePlatform = async (val) => {
  if (!val) return
  try {
    const res = await getShopList({
      platform_ids: [val]
    })
    shopOptions.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {

      if (form.value.api_active_status == 1 && !form.value.api_token) {
        ElMessage.error('请输入Token')
        return
      }

      if (form.value.api_active_status == 1 && !form.value.api_app_key) {
        ElMessage.error('请输入App Key')
        return
      }

      if (form.value.api_active_status == 1 && !form.value.api_app_key) {
        ElMessage.error('请输入API地址')
        return
      }

      if (form.value.sku_more_location_status == 1 && (!form.value.max_location_num || form.value.max_location_num <= 1)) {
        ElMessage.error('产品最大货位数必填，且数量大于1')
        return
      }

      loading.value = true

      if (form.value.id) {
        updateWarehouse(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      } else {
        savaWarehouse(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    }
  })
}
const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}

.title {
  font-weight: bold;
  padding-left: 6px;
  position: relative;
  margin-bottom: 10px;
  font-size: 16px;
}

.title::before {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  top: 5px;
  width: 2px;
  height: 14px;
  background: #3366F1;
}
</style>
